<?php
class Admin extends MX_Controller {

	function __construct() {
		parent::__construct();
		$this->load->database();
		$this->load->library('grocery_crud');
		$this->load->library(array('form_validation','session'));
		$this->load->helper('url');
		$this->load->model('admin_model', 'm', true);		
	}

	function _view_output($output = null) {
		if($this->session->userdata('groupId') != 1){
			redirect(site_url('admincp/login'));
		}
		
		$this->load->view('admin.php',$output);
	}

	

	function index() {
		$this->load->library('OnlineUsers');
		$this->load->library('visit_counter');
		
		$data['visit_counter'] = $this->visit_counter->getVisitCounter();
		$data['allVisits'] = $this->visit_counter->getAllVisit();
		@$output->output = $this->load->view('dashboard',$data, true);
		$output->title = "Thống kê lượng truy cập";
		$output->css_files = array();
		$output->js_files = array();
		
		$this->_view_output($output);
	}

	function login() {
		$this->load->view('login.php');	
	}
	
	public function dologin(){				
		$email=$this->input->post('email');
		$password=$this->input->post('password');
		$this->form_validation->set_rules('email', 'Tài khoản', 'required');
		$this->form_validation->set_rules('password', 'Mật khẩu', 'required');
		if ($this->form_validation->run()){
			$password=md5($password);			
			if($this->m->checkLogin($email,$password)){				
				if($this->session->userdata('groupId') == 1){
					redirect(site_url('admincp/'));
				}
			}else{
				//set messenge
				$data['error']="Đăng nhập không thành công";
				$this->load->view('login.php', $data);
				return;
			}
		}
		$data['error']=validation_errors();
		$this->load->view('login.php', $data);
	}

	public function logout(){
		$this->session->unset_userdata('email');
		$this->session->unset_userdata('groupId');
		redirect(site_url('admincp/login'));
	}

	function contacts () {
		$crud = new grocery_CRUD();
		$crud->set_table("contacts");
		$crud->columns("firstname","lastname","email","message");
		$crud->display_as("id","id")
			->display_as("firstname","Họ")
			->display_as("lastname","Tên")
			->display_as("email","Email")
			->display_as("message","Nội dung")
			->display_as("created_at","created_at");
		$crud->edit_fields("firstname","lastname","email","message");
		$crud->change_field_type("created_at", "hidden", date('Y-m-d H:i:s'));
		$crud->add_fields("firstname","lastname","email","message","created_at");
		$crud->set_subject("contacts");
		$output = $crud->render();
		$output->title = "contacts";
		$this->_view_output($output);
	}

	function pages() {
		$crud = new grocery_CRUD();
		$crud->set_table("pages");
		$crud->columns("type","title","description","data");
		$crud->display_as("type","Loại trang")
			->display_as("title","Tiêu đề")
			->display_as("description","Trích dẫn")
			->display_as("data","Nội dung");
		
		$crud->set_subject("Trang");
		$output = $crud->render();
		$output->title = "Quản lý trang";

		//validate
		$crud -> set_rules('type', 'Trang', 'required');
		$crud -> set_rules('title', 'Tiêu đề trang', 'required');
		$crud -> set_rules('data', 'Nội dung trang', 'required');

		$this->_view_output($output);
	}

	function galleries () {
		$crud = new grocery_CRUD();
		$crud->set_table("galleries");
		$crud->columns("title","image","caption","link");
		$crud->display_as("id","id")
			->display_as("title","Tiêu đề")
			->display_as("image","Hình ảnh (750 x 470)")
			->display_as("caption","Ghi chú")
			->display_as("link","Liên kết")
			->display_as("status","Trạng thái")
			->display_as("order","Sắp xếp");
		$crud->edit_fields("title","image","caption","link");
		$crud->add_fields("title","image","caption","link");

		$crud -> set_field_upload('image', 'uploads/slides');

		$crud->set_subject("Slide");

		//validate
		$crud -> set_rules('title', 'Tiêu đề', 'required');
		$crud -> set_rules('image', 'Hình ảnh', 'required');
		$crud -> set_rules('caption', 'Nội dung', 'required');
		$crud -> set_rules('link', 'Link liên kết', 'required');

		$output = $crud->render();
		$output->title = "Quản lý slide";
		$this->_view_output($output);
	}

	function groups () {
		$crud = new grocery_CRUD();
		$crud->set_table("groups");
		$crud->columns("name","details");
		$crud->display_as("id","id")
			->display_as("name","Tên nhóm")
			->display_as("details","Ghi chú");
		$crud->edit_fields("name","details");
		$crud->add_fields("name","details");
		$crud->set_subject("Nhóm");
		//validate
		$crud -> set_rules('name', 'Tên nhóm', 'required');

		$output = $crud->render();
		$output->title = "Quản lý nhóm";
		$this->_view_output($output);
	}

	function post_categories () {
		$crud = new grocery_CRUD();
		$crud->set_table("post_categories");
		$crud->columns("name","details");
		$crud->display_as("id","id")
			->display_as("name","Danh mục")
			->display_as("details","Ghi chú");
		$crud->edit_fields("name","details");
		$crud->add_fields("name","details");
		$crud->set_subject("post_categories");
		$output = $crud->render();
		$output->title = "post_categories";
		$this->_view_output($output);
	}

	function pro_categories () {
		$crud = new grocery_CRUD();
		$crud->set_table("pro_categories");
		$crud->columns("name", "parentId", "display");
		$crud->display_as("id","id")
			->display_as("name","Tên danh mục")
			->display_as("parentId","Menu cha")
			->display_as("display","Hiển thị");

		$crud->edit_fields("name", "parentId", "display");
		$crud->add_fields("name", "parentId", "display");
		$crud->set_subject("Danh mục");

		$parent = $this->m->getCategoryParent();
		$aryParrent[0] = 'Menu Chính';
		foreach ($parent as $key => $value) {
			$aryParrent[$value->id] = $value->name;
		}
		$crud->change_field_type('parentId', 'dropdown', $aryParrent);
		$crud->change_field_type('display', 'dropdown', array( '0' => 'Hiển thị','1' => 'Không hiển thị'));

		//validate
		$crud -> set_rules('name', 'Tên danh mục', 'required');
		$crud -> set_rules('parentId', 'Menu cha', 'required');

		$output = $crud->render();
		$output->title = "Quản lý danh mục";
		$this->_view_output($output);
	}

	function products () {
		$crud = new grocery_CRUD();

		$crud->set_table("products");
		$crud->columns("productId","name","images","catId","price", "new_flg");
		$crud->display_as("productId","Mã sản phẩm")
			->display_as("name","Tên sản phẩm")
			->display_as("description","Thuộc tính")
			->display_as("images","Hình ảnh (306 x 440) px")
			->display_as("catId","Danh mục")
			->display_as("price","Giá")
			->display_as("color","Màu")
			->display_as("size","Kích thước")
			->display_as("brand","Nhà sản xuất")
			->display_as("fb","Link Facebook")
			->display_as("new_flg","Hàng mới")
			->display_as("created_at","created_at");
		$crud->edit_fields("productId", "name","description","images","catId","price", "fb", "new_flg");
		$crud->change_field_type("created_at", "hidden", date('Y-m-d H:i:s'));
		$crud->add_fields("productId","name","description","images","catId","price", "fb", "new_flg");
		$crud->set_field_upload('images', 'uploads/products/thumbs');
		//306 * 440
		$crud->field_type('new_flg', 'dropdown', array( '0' => 'Không','1' => 'Hàng mới'), $default_value = 'Không');

		$crud -> set_relation('catId', 'pro_categories', '{name}', array('parentId <>' => '0', 'display' => '0'));
		$crud->add_action('Thêm ảnh', 'assets/grocery_crud/add_image.jpg', '','ui-icon-plus', array($this, 'make_product_images'));
		$crud->set_subject("Sản phẩm");

		//validate data
		if($crud->getState() === 'add') {
			$crud -> set_rules('productId', 'Mã sản phẩm', 'required|is_unique[products.productId]');
		} else {
			$crud -> set_rules('productId', 'Mã sản phẩm', 'required');
		}
		
		$crud -> set_rules('name', 'Tên sản phẩm', 'required');
		$crud -> set_rules('images', 'Hình ảnh sản phẩm', 'required');
		$crud -> set_rules('catId', 'Danh mục sản phẩm', 'required');
		$crud -> set_rules('price', 'Giá sản phẩm', 'required');


		$output = $crud->render();
		$output->title = "Quản lý sản phẩm";
		$this->_view_output($output);
	}

	function make_product_images($primary_key , $row) {
		return site_url('admincp/product_images').'/'.$row->id;
	}

	function product_images($id) {
		$this->load->model('product_model', 'product', true);
		$data = $this->product->find_by_primary($id);


		$this->load->library('image_CRUD');
		$image_crud = new image_CRUD();
		$image_crud->set_module('administrator');
		$image_crud->set_primary_key_field('id');
		$image_crud->set_url_field('image');
		$image_crud->set_table('pro_images')
		->set_relation_field('productId')
		->set_image_path('uploads/products/images');
		//360 * 520
		$output = $image_crud->render();
		$output->title = 'Quản lý hình ảnh '.$data->productId . ' | '. $data->name ."<br/><br/>" .'Kích thước yêu cầu: (360 x 520)';
		$this->_view_output($output);
	}

	function users () {
		$crud = new grocery_CRUD();
		$crud->set_table("users");
		$crud->columns("email","password","groupId");
		$crud->display_as("id","id")
			->display_as("firstname","Họ")
			->display_as("lastname","Tên")
			->display_as("email","Email")
			->display_as("password","Mật khẩu")
			->display_as("address","Địa chỉ")
			->display_as("phone","Số điện thoại")
			->display_as("groupId","Nhóm")
			->display_as("created_at","created_at")
			->display_as("updated_at","updated_at")
			->display_as("deleted_flg","deleted_flg");
		$crud -> set_relation('groupId', 'groups', '{name}');
		//validator
		$crud -> set_rules('password', 'Mật khẩu', 'required');
		$crud -> set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
		$crud -> set_rules('groupId', 'Nhóm', 'required');


		$crud->edit_fields("firstname","lastname","email", "address","phone","groupId","updated_at");
		$crud->change_field_type("created_at", "hidden", date('Y-m-d H:i:s'));
		$crud->change_field_type("updated_at", "hidden", date('Y-m-d H:i:s'));
		$crud->change_field_type('password', 'password');
		$crud->add_fields("email","password","groupId","created_at","updated_at");

		//call back
		//add action
		$crud->add_action('Change password', 'assets/grocery_crud/change-password-icon.png', 'admincp/change_password','ui-icon-plus');


		$crud->set_subject("Thành viên");
		$crud->callback_before_insert(array($this,'encrypt_password'));
		$crud->callback_before_update(array($this,'encrypt_password'));
		$output = $crud->render();
		$output->title = "Quản lý thành viên";
		$this->_view_output($output);
	}


	public function change_password($primary_key){
		$user=$this->m->getUser($primary_key);
		$data['mes']="";
		if($user){
			$data['user']=$user['email'];
			$data['id']=$user['id'];
		}else{
			$data['mes']="Tài khoản không tồn tại";
		}
		$output->output = $this->load->view('changepass',$data, true);
		$output->title = "change pass";
		$output->css_files = array();
		$output->js_files = array();
		
		$this->load->view('admin.php',$output);
	}

	public function dochangepass() {
		$password=$this->input->post('password');
		$email=$this->input->post('email');
		
		$this->form_validation->set_rules('password', 'Mật khẩu', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required');
		if ($this->form_validation->run()){
			if($this->m->changePass($email,md5($password))){
				$data['mes']="Đổi mật khẩu thành công";
				$output->output = $this->load->view('changepass',$data, true);
				$output->title = "change pass";
				$output->css_files = array();
				$output->js_files = array();
				$this->load->view('admin.php',$output);
			}
		} else {
			$this->change_password($this->input->post('id'));
		}
	}

	/////////////////////////////CALL BACK////////////////////////////////////
	
	/**
	 * Check exist Email
	 * return true if exist
	 * retrun false if not exist
	 */
	function existEmail($email) {
		if ($this -> m -> checkExistEmail($email)) {// exist user
			$this -> form_validation -> set_message('existEmail', 'Tài khoản đã tồn tại');
			return FALSE;
		}
		return TRUE;
	}

	/*
	 * Encrypt password
	 * input strpassword
	 * return Password encrypt
	 */
	function encrypt_password($post_array, $primary_key = null) {
	    $this->load->helper('security');
	    $post_array['password'] = md5($post_array['password']);
	    return $post_array;
    }
}
?>